package com.kuangstudy.controller.set;

import com.kuangstudy.vo.R;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Set;

/**
 * @author 飞哥
 * @Title: 学相伴出品
 * @Description: 我们有一个学习网站：https://www.kuangstudy.com
 * @date 2021/5/24 10:59
 */
@RestController
public class BbsRelationController {

    final static String FABULOUS_BBS_KEY = "fabulous:bbs:";

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 点赞
     *
     * @return
     */
    @PostMapping("/click/fabulous")
    public R fabulousbbs(Integer bbsid, Integer userid) {
        String result = "";
        try {
            Long add = this.redisTemplate.opsForSet().add(FABULOUS_BBS_KEY + bbsid, userid);
            return R.ok().data("isfabulous", add).message(add == 1 ? "点赞成功" : "你已经点赞过了...");
        } catch (Exception ex) {
            return R.error().message("服务器忙!");
        }
    }

    /**
     * 取消点赞
     *
     * @return
     */
    @PostMapping("/cancel/fabulous")
    public R cancelfabulousbbs(Integer bbsid, Integer userid) {
        String result = "";
        try {
            Long add = this.redisTemplate.opsForSet().remove(FABULOUS_BBS_KEY + bbsid, userid);
            return R.ok().data("isfabulous", add).message(add == 1 ? "取消成功" : "你已经取消过了...");
        } catch (Exception ex) {
            return R.error().message("服务器忙!");
        }
    }

    /**
     * 取消点赞
     *
     * @return
     */
    @PostMapping("/total/fabulous")
    public R totalfabulousbbs(Integer bbsid) {
        String result = "";
        try {
            Long size = this.redisTemplate.opsForSet().size(FABULOUS_BBS_KEY + bbsid);
            return R.ok().data("totalsize", size).message("共" + size + "人点赞");
        } catch (Exception ex) {
            return R.error().message("服务器忙!");
        }
    }


    /**
     * 获取点赞成员
     *
     * @return
     */
    @PostMapping("/list/fabulous")
    public R listfabulousbbs(Integer bbsid) {
        String result = "";
        try {
            Set members = this.redisTemplate.opsForSet().members(FABULOUS_BBS_KEY + bbsid);
            return R.ok().data("members", members);
        } catch (Exception ex) {
            return R.error().message("服务器忙!");
        }
    }

    /**
     * 判断用户是否点赞过
     *
     * @return
     */
    @PostMapping("/ismember/fabulous")
    public R ismemberfabulous(Integer bbsid, Integer userid) {
        String result = "";
        try {
            Boolean member = this.redisTemplate.opsForSet().isMember(FABULOUS_BBS_KEY + bbsid, userid);
            return R.ok().data("ismember", member ? "点赞过了" : "没有点赞");
        } catch (Exception ex) {
            return R.error().message("服务器忙!");
        }
    }

}
